﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace FB.Annotations
{
    public abstract class SecurityKeyOnlyBaseAttribute : System.Web.Mvc.AuthorizeAttribute
    {
        public SecurityKeyOnlyBaseAttribute() { }

        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            if (httpContext == null)
                throw new ArgumentNullException("httpContext");

            //never authorize someone who isn't logged in
            var user = httpContext.User;
            if (!user.Identity.IsAuthenticated)
                return false;

            var keyObject = GetSecurityKey();

            return null != keyObject && keyObject.ValidateUser() && !string.IsNullOrEmpty(keyObject.GetPassKey());
        }


        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {

            if (filterContext.HttpContext.Request.IsAjaxRequest())
            {
                // Set Forbidden Code
                //filterContext.HttpContext.Response.StatusCode = 403;
                filterContext.Result = GetJsonResultForUnauthorizedRequest(filterContext);
            }
            else
            {

                filterContext.Result = GetResultForUnauthorizedRequest(filterContext);
            }
        }


        public virtual JsonResult GetJsonResultForUnauthorizedRequest(AuthorizationContext filterContext)
        {
            var urlHelper = new UrlHelper(filterContext.RequestContext);
            var result = new FB.Data.Models.AjaxResultViewModel<object>
            {
                Status = false,
                Data = new { Code = 700, Url = urlHelper.Action("SecurityCheck", "Home", new { Area = "Admin" }) },
                Msg = "NotAuthorized",
            };

            return new JsonResult
            {
                Data = result,
                JsonRequestBehavior = JsonRequestBehavior.AllowGet
            };
        }


        public virtual ActionResult GetResultForUnauthorizedRequest(AuthorizationContext filterContext)
        {
            var urlHelper = new UrlHelper(filterContext.RequestContext);
            return new RedirectToRouteResult(
                    new RouteValueDictionary {
                            { "action", "SecurityCheck" },
                            { "controller", "Home" },
                            { "area", "Admin"},
                            { "returnUrl", filterContext.HttpContext.Request.RawUrl },
                        });
        }


        public virtual FB.Data.Models.ISecurityKey GetSecurityKey()
        {
            throw new NotImplementedException();
        }

    }
}
